package com.chat.controller;

import com.chat.bean.Login;
import com.chat.bean.Register;
import com.chat.bean.Userinfo;
import com.chat.service.LoginService;
import com.chat.util.Md5Util;
import com.chat.util.exception.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
public class LoginCtrl {
    @Autowired
    LoginService loginService;
    @GetMapping("/")
    public String tologin(){
        return "user/login";
    }
    /**
     * 登陆
     * */
    @PostMapping("/justlogin")
    @ResponseBody
    public R login(@RequestBody Login login, HttpSession session){
        login.setPassword(Md5Util.StringInMd5(login.getPassword()));
        String userid = loginService.justLogin(login);
        if(userid==null){
            return R.error().message("账号或者密码错误");
        }
        session.setAttribute("userid",userid);
        return R.ok().message("登录成功");
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public R userInfo(HttpSession session) {
        String userid = (String) session.getAttribute("userid");
        Userinfo info = loginService.getInfo(userid);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", info);
        return R.ok().data(map);
    }

    @GetMapping("/youInfo/{userid}")
    @ResponseBody
    public R userInfo(@PathVariable("userid") String userid ) {
        Userinfo info = loginService.getInfo(userid);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", info);
        return R.ok().data(map);
    }

    /**
     * 注册
     *
     */
    @PostMapping("/register")
    @ResponseBody
    public R register(@RequestBody Register register){
        int num = (int)(Math.random()*30);
        register.setUimg("/img/"+num+".jpg");
        register.setUsign("爱像圆周率，无限不循环。");
        boolean result = loginService.register(register);
        if(!result){
            return R.error().message("注册失败，请重试");
        }
        return R.ok().message("注册成功");
    }



}
